package library.net.retrofit.interceptor;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Created by qiang.hou on 2018/12/11.
 * @version 1.0
 */
public abstract class RxTokenInterceptor implements Interceptor {

    /**
     * IService接口中添加header，用于表示该接口是否必须携带token
     */
    public static final String HEADER_NEED_TOKEN = "NeedToken: true";
    public static final String HEADER_NO_NEED_TOKEN = "NeedToken: false";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder builder = original
                .newBuilder();
        String needToken = original.header("NeedToken");
        if (needToken == null || needToken.equals("true")) {
            builder.header("Authorization", getToken());
        }
        Request request = builder
                .removeHeader("NeedToken")
                .method(original.method(), original.body())
                .build();
        return chain.proceed(request);
    }

    protected abstract String getToken();
}
